﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;

namespace GameServer.Servers
{
    class Message
    {
        private byte[] data = new byte[1024];
        private int startIndex = 0;//我们存取了多少个字节的数据在数组里面

        //public void AddCount(int count)
        //{
        //    startIndex += count;
        //}
        public byte[] Data
        {
            get { return data; }
        }
        public int StartIndex
        {
            get { return startIndex; }
        }
        public int RemainSize
        {
            get { return data.Length - startIndex; }
        }
        /// <summary>
        /// 解析数据或者叫做读取数据
        /// </summary>
        public void ReadMessage(int newDataAmount, Action<RequestCode,ActionCode,string> processDataCallback )
        {
            startIndex += newDataAmount;
            while (true)
            {
                if (startIndex <= 4) return;//说明甚至消息长度都没有解析出来——不处理
                int count = BitConverter.ToInt32(data, 0);//从data数组索引0开始，读取4个字节，转成int——消息的长度
                //减去前4个字节后，如果剩余长度大于count
                if ((startIndex - 4) >= count)//说明消息接收完整
                {
                    //Console.WriteLine(startIndex);
                    //Console.WriteLine(count);
                    //string s = Encoding.UTF8.GetString(data, 4, count);
                    //Console.WriteLine("解析出来一条数据：" + s);
                    RequestCode requestCode = (RequestCode)BitConverter.ToInt32(data, 4);//从data数组索引4开始，读取4个字节，转成int—— RequestCode
                    ActionCode actionCode = (ActionCode)BitConverter.ToInt32(data, 8);//从data数组索引8开始，读取4个字节，转成int——ActionCode
                    string s = Encoding.UTF8.GetString(data, 12, count-8);//从data数组索引12开始，读取count-8个字节，得到真正的消息内容
                    processDataCallback(requestCode, actionCode, s);
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
        }
        public static byte[] PackData(ActionCode actionCode,string data)
        {
            //消息 = 长度 + actionCode + data
            byte[] actionCodeBytes = BitConverter.GetBytes((int)actionCode);//把actionCode转成4位二进制
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);//把真实消息转成二进制数组
            int dataAmount = actionCodeBytes.Length + dataBytes.Length;//得到有效消息的总长度
            byte[] dataAmountBytes = BitConverter.GetBytes(dataAmount);//把消息长度转成4位二进制
            byte[] newBytes =dataAmountBytes.Concat(actionCodeBytes).ToArray<byte>();//Concat(dataBytes);
            return newBytes.Concat(dataBytes).ToArray<byte>();
        }
    }
}
